package nio;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Created by Administrator on 2017/10/20 0020.
 */
public class Channel2
{
    public static void main(String[] args) throws Exception
    {
//        File f = new File("D:\\itellijIdea_wk\\JavaDemo\\src\\nio\\2.txt");
//        RandomAccessFile file = new RandomAccessFile(f, "rw");
//        FileChannel channel = file.getChannel();
//        MappedByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, f.length());
//        channel.position(f.length());
//        channel.write(buf);
//        buf.clear();

        for (int i = 0; i < 10000; i++)
        {
            write("D:\\itellijIdea_wk\\JavaDemo\\src\\nio\\2.txt", "中\n");
        }

        if (randomFile != null)
        {
            try
            {
                randomFile.close();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    private static RandomAccessFile randomFile = null;
    public static void write(String fileName, String content)
    {
        try
        {
            if(randomFile == null)
            {
                randomFile = new RandomAccessFile(fileName, "rw");
            }
            long fileLength = randomFile.length();
            randomFile.seek(fileLength);
            randomFile.write(content.getBytes());
        } catch (IOException e)
        {
            e.printStackTrace();
            if (randomFile != null)
            {
                try
                {
                    randomFile.close();
                } catch (IOException e2)
                {
                    e2.printStackTrace();
                }
            }
        }
    }
}
